package com.atguigu.tingshu.search.runners;

import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.List;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.search.runners
 * @Project：tingshu_parent240829
 * @name：DistroBloomFilterInitListener
 * @Date：2025/2/14 18:31
 * @Filename：DistroBloomFilterInitListener
 */
@Component
@Slf4j
public class DistroBloomFilterInitListener implements SpringApplicationRunListener {


    /*
     * @description: TODO 在spring刷新完毕springboot启动过程中会回调该方法
     *                ConfigurableApplicationContext:spring bean方法
     * started会回调两次
     * @author: yyj
     * ApplicationArguments:获取应用启动时指定的命令行参数
     * @date: 2025-02-14
     */
    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        //初始化布隆过滤器
        boolean containsBean = context.containsBean("rbloomFilter");

        if (containsBean){
            //1.获取布隆过滤器对象
            RBloomFilter rbloomFilter = context.getBean("rbloomFilter", RBloomFilter.class);
            long count = rbloomFilter.count();
            if (count==0){
                //2.获取数据
                ItemServiceImpl itemServiceImpl = context.getBean("itemServiceImpl", ItemServiceImpl.class);
                List<Long> albumdIds = itemServiceImpl.getAlbumdIds();

                //存放数据
                if (!CollectionUtils.isEmpty(albumdIds)){
                    for (Long albumdId : albumdIds) {
                        rbloomFilter.add(albumdId);
                    }
                    log.info("获取到元素个数为:{}",rbloomFilter.count());
                }
            }
        }
    }
}